package com.obuge.yfly.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
//import com.obuge.yfly.entity.MySession;
import com.obuge.yfly.entity.MySession;
import com.obuge.yfly.mapper.MySessionMapper;
import com.obuge.yfly.util.RedisUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MySessionMapper mySessionMapper;
    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器的preHandle方法");
        String method = request.getMethod();
        String token = request.getHeader("token");
        if(method.equals("OPTIONS")) return true;
        if(StringUtil.isNullOrEmpty(token)){
            throw new CustomerException(400,"缺少token");
        }else{
            MySession sessionData = mySessionMapper.selectById(token);
            if(sessionData == null){
                throw new CustomerException(400,"请重新登录");
            }else if(System.currentTimeMillis() - sessionData.getCreateTime()> 2 * 60 * 60 * 1000){
                throw new CustomerException(400,"登录已过期");
            }else{
                request.setAttribute("session",sessionData);
                //request.getAttribute("session");
            }
        }
        return true;
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行了拦截器的afterCompletion方法");
    }
}